﻿using System.Threading.Tasks;
using IOP.Models.Message.MQTT;
using IOP.Models.Message.MQTT.Package;

namespace IOP.Pulsar.MQTT.Result
{
    /// <summary>
    /// 连接结果
    /// </summary>
    public class ConnectResult : MQTTResult
    {
        /// <summary>
        /// 回执包
        /// </summary>
        private ConnackPackage Package { get; set; }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="type"></param>
        public ConnectResult(ReturnCodeType type)
        {
            Package = new ConnackPackage(false, type);
        }
        /// <summary>
        /// 执行结果
        /// </summary>
        /// <param name="context"></param>
        public override void ExcuteResult(MQTTContext context)
        {
            var connect = (ConnectPackage)context.Request.Package;
            if(Package.ConnectReturnCode != ReturnCodeType.Accept)
            {
                context.Response.Package = new ConnackPackage(false, Package.ConnectReturnCode);
                context.Response.SendAndClose(Package);
                return;
            }
            else
            {
                if (connect.WillFlag)
                {
                    var packetId = context.Session._TopicCenter.CreatePacketIdentifier();
                    var willPackage = new PublishPackage(connect.WillTopic, packetId, connect.WillMessage, connect.WillQoS);
                    context.Session.WillPackages.Add(willPackage);
                }
                ConnackPackage result;
                if (connect.CleanSession)
                    result = new ConnackPackage(false, ReturnCodeType.Accept);
                else
                    result = new ConnackPackage(true, ReturnCodeType.Accept);
                context.Response.Package = result;
                context.Response.SendPackage(Package);
            }
        }
        /// <summary>
        /// 执行结果(异步)
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task ExcuteResultAsync(MQTTContext context)
        {
            return Task.Run(() =>
            {
                ExcuteResult(context);
            });
        }
    }
}
